package org.xdq.demo.url.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xdq.demo.url.dao.UrlDao;
import org.xdq.demo.url.model.UrlInfo;
import org.xdq.demo.url.service.UrlService;

import java.util.List;

@Service
@Transactional
public class UrlServiceImpl implements UrlService {

    private static final String SHORT_URL_KEY = "SHORT_URL_KEY";

    private static String to62(long cnt){
        String bits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        if(cnt<bits.length()){
            int i = (int)cnt;
            return bits.substring(i,i+1);
        }
        int i = (int)(cnt%bits.length());
        return new StringBuilder(to62(cnt/bits.length())).append(bits.substring(i,i+1)).toString();
    }

    @Autowired
    private UrlDao urlDao;

    @Autowired
    private RedisTemplate redisTemplate;




    @Override
    public void addUrl(UrlInfo urlInfo) {


        long cnt = redisTemplate.opsForValue().increment(SHORT_URL_KEY);

        String str = to62(cnt);

        urlInfo.setUrl_short(to62(cnt));
        urlDao.insertUrl(urlInfo);

    }

    @Override
    public String getUrlSrc(String url) {
        return urlDao.getUrlSrc(url);
    }

    @Override
    public List<UrlInfo> getUrlList() {
        return urlDao.getUrlList();
    }


}
